package com.ruoyi.web.core.config;

import com.cyl.h5.service.H5MemberService;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.service.MemberLogininforService;
import com.cyl.manager.ums.service.MemberService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginMember;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysDeptService;

import cn.hutool.core.codec.Base64;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class H5MemberInterceptor extends HandlerInterceptorAdapter {

  @Autowired
  private TokenService tokenService;
  @Autowired
  private MemberService memberService;
  @Autowired
  private ISysDeptService deptService;
  
  @Autowired
  private H5MemberService h5MemberService;
  @Autowired
  private RedisCache redisCache;

  private static String[] WHITE_PATHS = {
          "/h5/sms/login",
          "/h5/wechat/login",
          "/h5/account/login",
          "/h5/register",
          "/h5/validate"
  };

  @SuppressWarnings("deprecation")
@Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String requestUri = request.getRequestURI();
    boolean flag = true;
    if (!requestUri.startsWith("/h5/")) {
      return super.preHandle(request, response, handler);
    }

    for (String s : WHITE_PATHS) {
      if (requestUri.startsWith(s)) {
        flag = false;
        break;
      }
    }
    if (!flag) {
      return super.preHandle(request, response, handler);
    }
    LoginMember loginMember = tokenService.getLoginMember(request);
    if (loginMember == null) {
      throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
    }
    tokenService.verifyMemberToken(loginMember);
    
    //缓存120分钟会员信息//
    String memberKey = Constants.MEMBER_INFO+"_"+loginMember.getMemberId();
    Member member = redisCache.getCacheObject(memberKey);
    

    if(member==null) {
    	 //获取会员信息
			Map<String, Object> params = new HashMap<String, Object>();
            member = memberService.selectById(loginMember.getMemberId());
            if(member != null && member.getNickname()!=null) {
		        params.put("nickname", URLEncoder.encode(Base64.encode(member.getNickname())));
            }

          Long deptDpId = member.getDeptDpId();//店铺部门id
          if(deptDpId == null) {
      		SysDept sysDept = deptService.selectDeptById(deptDpId);
      		if(sysDept!=null) {
      	        params.put("dpmc", sysDept.getDeptName());
      	       
      		}
            h5MemberService.insertLogininfor(member);
          }
          member.setParams(params);
          redisCache.setCacheObject(memberKey, member,60*4,TimeUnit.MINUTES);
    }
   
    if (member == null || member.getStatus() == 0) {
      throw new ServiceException("获取用户ID异常。", HttpStatus.UNAUTHORIZED);
    }
    
    if (member != null && member.getHyzt() !=null && member.getHyzt().intValue() == 2 ) {
        throw new ServiceException("用户获取状态异常！code=2。用户id：" + member.getId(), HttpStatus.UNAUTHORIZED);
    }
    
    if (requestUri.startsWith("/h5/shop")) {//如果是访问的店铺相关接口判断用户身份
        Long deptDpId2 = member.getDeptDpId();//店铺部门id
    	Integer rolezd = member.getRolezd();//客户身份 0->普通用户；1->核销员；2->团长
    	if(deptDpId2 == null || rolezd == null || rolezd.intValue()==0) {
    	      throw new ServiceException("权限不足！", HttpStatus.UNAUTHORIZED);
    	}
    }
 
    //将会员信息存放至全局
    LocalDataUtil.setVar(Constants.MEMBER_INFO, member);

    return super.preHandle(request, response, handler);
  }



}
